#!/usr/bin/perl -w

####################################################
# Copyright (c) 2002-2007 BioWare Corp.
# http://www.bigdaddymonitor.org
#
# This file is part of the BigDaddy Monitoring
# program. It is free software distributed under
# the terms of the BSD License. It is ditributed
# in the hopes that it will be useful, but
# WITHOUT ANY WARRANTY; without event the implied
# warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
#
# The BSD License is available from:
# http://www.opensource.org/licenses/bsd-license.php
####################################################

#===================================================================================================
# BigDaddy Process Monitor
# Monitors the BigDaddy processes and restarts or functions as need be
# Dups 24.03.2004
#===================================================================================================

BEGIN
{
	push(@INC,'/bigdaddy')
}

use strict;
use Config::IniFiles;
use BioMain qw(:allfunctions);
use DBI;

#===================================================================================================
#Before we do anything we are going to bring up the main ini file: bigdaddy.ini should be in the
#same dir as these executables.
my $bigdaddy_cfg= new Config::IniFiles( -file => "/bigdaddy/bigdaddy.ini" );

#Get the dbini handle
my $dbIniHandle = $bigdaddy_cfg->val('main', 'dbinihandle');

#Get the mailserver
my $mailServer = $bigdaddy_cfg->val('main', 'smtpserver');

if (!defined($mailServer) || $mailServer eq '')
{
	$mailServer = "localhost";
}

#Get the Global From Email
my $fromEmail = $bigdaddy_cfg->val('main', 'fromemail');

#Get the Global From Email
my $normalEmail = $bigdaddy_cfg->val('main', 'noncriticalrestart');

#Get the Global From Email
my $superBadEmail = $bigdaddy_cfg->val('main', 'criticalrestart');

require ("/bigdaddy/bigdaddy_common.pl");

#===================================================================================================

my $dbb = callfor_db_handle($dbIniHandle, 0, 99);

if (defined($dbb))
{
	my $crontabIni="servermon";

	my $sql="SELECT inifile, ID FROM inifile WHERE ID IN ('".$crontabIni."')";
	my $result=$dbb->prepare( $sql );
	$result->execute;

	while (my $ref=$result->fetchrow_hashref())
	{
	    open (TMPINIFILE, ">/tmp/cron".$ref->{'ID'}.".ini") or die "Could not open temp file for writing: $!";
	    print TMPINIFILE $ref->{'inifile'};
	    close (TMPINIFILE) or die "Could not close temp file: $!";
	}

	my $cfg_crontab= new Config::IniFiles( -file => "/tmp/cron".$crontabIni.".ini" );

	# Check for the crontab delay value
	my $delay=$cfg_crontab->val('global','globaldelay');
	my $status=$cfg_crontab->val('global','globalstatus');


	# if the status is currently set to delay and the delay time is less than the current
	# time then set the delay to 0, enable it and put the last_ranenabled to the current time.
	if ($status eq 'on')
	{
		#Now for each process we need to open the processfile
		#These two array indexes should match
		my @processFileArray = qw(server_monitor.process crontab_monitor.process external_check.process internal_check.process server_group_monitor.process);
		my @processArray = qw(servermon crontabmon excheck intcheck groupmon);
		
		for (my $i=0; $i<scalar(@processFileArray); $i++)
		{
			my $processFile="/bigdaddy/logs/".$processFileArray[$i];
			open(PROCESSFILE, $processFile) || die("Could not open file $processFile: $!");
			my @sContents=<PROCESSFILE>;
			close(PROCESSFILE);
			
			foreach my $sTime (@sContents)
			{
				if ((time()-600)>$sTime)
				{
					#If this action already has been performed, there seems to be
					#some problem restarting Bigdaddy
					if (-e $processFile.".0")
					{
						&send_mail($superBadEmail, "Cannot Start BigDaddy: ".$processArray[$i], "Cannot Start BigDaddy: ".$processArray[$i], $fromEmail, $mailServer  );
					}
					else
					{
						&checkProcess($processArray[$i], $normalEmail);
						
						#Write in an action for this process
						&SetProcessTime($processFile.".0");
					}
				}
				else
				{
					#getrid of any weird process files kicking around
					if (-e $processFile.".0")
					{
						unlink($processFile.".0");
					}
				}
			}

		}
	}
}
else
{
	#Database not available.
	&send_mail($superBadEmail, "BigDaddy Database Unavailable", "BigDaddy Database Unavailable", $fromEmail, $mailServer  );

}


#===================================================================================================
# checkProcess(string $processID)
# Restartes the bigdaddy process and sends a message
#===================================================================================================
sub checkProcess
{
	my ($process, $emailString) = @_;

	if ($process eq 'crontabmon')
	{
		system("/bigdaddy/bigdaddy restart crontabmonitor");
	}
	elsif ($process eq 'servermon')
	{
		system("/bigdaddy/bigdaddy restart servermon");
	}
	elsif ($process eq 'excheck')
	{
		system("/bigdaddy/bigdaddy restart excheck");
	}
	elsif ($process eq 'intcheck')
	{
		system("/bigdaddy/bigdaddy restart intcheck");
	}
	elsif ($process eq 'groupmon')
	{
		system("/bigdaddy/bigdaddy restart groupmon");
	}

	&send_mail($emailString, "Restarted BigDaddy Process: ".$process, "Restarted BigDaddy Process: ".$process, $fromEmail, $mailServer  );
}




